package com.example.leetdemo.plan1;

import java.util.Stack;

public class Sword036 {

    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < tokens.length; i++) {
            if (tokens[i].equals("+") || tokens[i].equals("*")
                    || tokens[i].equals("-") || tokens[i].equals("/")) {
                calculator(stack, tokens[i]);
            } else {
                stack.push(Integer.parseInt(tokens[i]));
            }

        }
        return stack.size() > 0 ? stack.pop() : 0;
    }

    private void calculator(Stack<Integer> stack, String str) {
        int b = stack.pop(), a = stack.pop();
        if (str.equals("+")) {
            stack.push(a + b);
        }
        if (str.equals("-")) {
            stack.push(a - b);
        }
        if (str.equals("*")) {
            stack.push(a * b);
        }
        if (str.equals("/")) {
            stack.push(a / b);
        }
    }
}
